package com.dmxh.config;

import com.dmxh.realm.Realm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {


    @Bean
    //使用HashCredentialMatcher可以通过hash的方式存储,不会显示明文,安全性更高
    public HashedCredentialsMatcher     hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //加密算法名称
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        //迭代次数
        hashedCredentialsMatcher.setHashIterations(7);
        //是否采用16进制转换
        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);
        return hashedCredentialsMatcher;
    }

    //通过配置类向spring容器中添加realm组件
    @Bean
    public Realm shiroRealm() {
        Realm shiroRealm = new Realm();
        shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return shiroRealm;
    }

    //通过realm组件创建DefaultWebSecurityManager对象
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager() {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(shiroRealm());
        return defaultWebSecurityManager;
    }

    //通过DefaultWebSecurityManager对象创建ShiroFilterFactoryBean对象
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean() {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager());
//        HashMap<String, Filter> stringFilterHashMap = new HashMap<>();
//        HashMap<String, String> stringStringHashMap = new HashMap<>();
//        stringStringHashMap.put("/login", DefaultFilter.anon.name());
//        shiroFilterFactoryBean.setFilters(stringFilterHashMap);
//        shiroFilterFactoryBean.setFilterChainDefinitionMap(stringStringHashMap);
        return shiroFilterFactoryBean;
    }

}
